<?php

namespace App\Ad\Docking;

use App\Ad\MediaApi\MediaApiBase;
use App\Commons\CommonConstant;
use App\Datalog\AdMonitorLog;
use App\Models\AdMonitor;
use App\Models\AdPlan;
use App\Models\FirstupAd;
use App\Models\Log\LogAdMonitor;
use App\Models\Log\LogAdMonitorInfo;
use App\Models\Log\LogAdPostbackMedia;
use Illuminate\Http\Request;
use YQ\YqExtend;

// 百度信息流-小程序
class BaiduxxlMicroGame extends DockingBase
{
    // 点击监控参数
    // https://dev2.baidu.com/content?sceneType=0&pageId=103228&nodeId=769&subhead=
    protected $monitorParams = [
        'pid'           => '__PLAN_ID__',        // 计划ID
        'uid'           => '__UNIT_ID__',        // 单元ID
        'aid'           => '__IDEA_ID__',        // 创意ID
        'userid'        => '__USER_ID__',        // 账户ID
        'click_id'      => '__CLICK_ID__',       // 点击或曝光唯一标识
        'idfa'          => '__IDFA__',           // IOS设备标识
        'imei_md5'      => '__IMEI_MD5__',       // Android设备标识
        'android_id'    => '__ANDROIDID1__',     // Android设备标识
        'androidid_md5' => '__ANDROIDID__',      // Android设备标识
        'ip'            => '__IP__',             // IP地址
        'ua'            => '__UA__',             // 数据上报终端设备
        'os'            => '__OS__',             // 操作系统类型
        'ts'            => '__TS__',             // 时间戳
        // 'ext_info'      => '__EXT_INFO__',       // 广告信息透传字段
        'mac_md5'       => '__MAC1__',           // Android设备标识
        'mac'           => '__MAC__',            // Android设备标识
        'oaid'          => '__OAID__',           // Android广告标志
        'oaid_md5'      => '__OAID_MD5__',       // Android广告标志
        'comb_id'       => '__COMBID__',         // 程序化创意组合ID
        'size'          => '__SIZE__',           // 屏幕尺寸
        'deeplink_url'  => '__DEEPLINK_URL__',   // 调起url
        'bd_vid'        => '__BD_VID__',         // 点击、曝光唯一标识
        'callback_url' => '__CALLBACK_URL__',    // 效果数据回传URL
    ];

    // 转化类型映射
    protected $eventTypeMap = [
        CommonConstant::EVENT_FIRSTUP => 4,
        CommonConstant::EVENT_REG     => 25,
        CommonConstant::EVENT_PAY     => 26,
    ];

    // 此接口由子类继承
    // 获得点击监控链接拼接参数
    public function getMonitorParams($device_type): string
    {
        return http_build_query($this->monitorParams);
    }

    // 此接口由子类继承
    // 处理落地监控数据
    public function handleMonitorInfo(Request $request)
    {
        // 待匹配日志
        $params           = $request->all();
        $log              = LogAdMonitor::suffix(date('Ym'));
        $log->create_time = time();
        $log->plan_id     = $params['plan_id'];
        $log->ip          = $params['ip'] ?? YqExtend::getIP();
        $log->click_id    = $params['bd_vid'] ?? $params['click_id'];
        $log->save();

        // 完整日志
        $info              = LogAdMonitorInfo::suffix(date('Ym'));
        $info->create_time = time();
        $info->plan_id     = $params['plan_id'];
        $info->monitor_id  = $log->id;
        $info->data        = json_encode($params, JSON_UNESCAPED_UNICODE);
        $info->save();

        // 落地日志
        AdMonitorLog::getInstance()->addLog($log, $info);

        return yqok();
    }

    /**
     * 此接口由子类继承
     * 根据媒体加密方式-生成对应的设备码，用于匹配
     * @param int      $device_type 设备类型
     * @param string[] $device_nums 设备码
     * @return array
     */
    public function getMonitorDeviceNum($device_type, $device_nums): array
    {
        $data = [];
        foreach ($device_nums as $key => $val) {
            switch ($key) {
                case 'click_id':
                    $data[$key] = $val;
                    break;
            }
        }

        return $data;
    }

    /**
     * 此接口由子类继承
     * 将用户行为进行api上报转化，如激活注册付费
     * 文档地址：https://docs.qingque.cn/d/home/eZQDnexll3-ebbtlX3xEDvBN3?identityId=1js2qROclGd#section=h.nxehxee2186m
     * @param int $event_type 事件类型 如激活注册付费
     * @param AdMonitor $monitor
     * @param FirstupAd $firstup_ad
     * @param mixed $mod 事件对应的模型 激活 Firstup 注册 Users 付费 Orders
     * @return int 处理结果状态
     */
    public function postbackToMedia($event_type, AdMonitor $monitor, FirstupAd $firstup_ad, $mod): int
    {
        // 此事件不需要上报
        if (!isset($this->eventTypeMap[$event_type])) {
            return LogAdPostbackMedia::STATUS_NONEED;
        }

        $plan = AdPlan::find($firstup_ad->plan_id);
        if ($plan['access_type'] != AdPlan::ACCESS_TYPE_API) {
            return LogAdPostbackMedia::STATUS_NOTAPI;
        }

        $monitor_data = json_decode($monitor->data, true);

        $params = [
            'token'           => 'rwS5N8q57kh3j4It3rT7tO6Iiv6Nuci6@EMlmkz3Uut8U5GRM2ISjL9FI5lmgzdhf',
            'conversionTypes' => [
                [
                    'logidUrl'    => 'https://aisite.wejianzhan.com/site/wjz7lb38/4ae018c3-948d-453c-8665-4729fdbf4533&bd_vid=' . $monitor_data['bd_vid'],
                    'newType'     => (int)$this->eventTypeMap[$event_type],
                    'convertTime' => time(),
                ]
            ],
        ];

        if ($event_type == CommonConstant::EVENT_PAY) {
            $params['conversionTypes'][0]['convertValue'] = (int)($mod->call_money * 100);
        }

        $url    = 'https://ocpc.baidu.com/ocpcapi/api/uploadConvertData';
        $header = ['Content-Type: application/json; charset=utf-8'];
        $res    = MediaApiBase::getInstance()->curl($url, $params, true, true, 5, false, $header);
        if ($res[0] != 200) {
            return LogAdPostbackMedia::STATUS_FAIL;
        }

        $ret = json_decode($res[1], true);
        if ($ret['header']['status'] != 0) {
            return LogAdPostbackMedia::STATUS_FAIL;
        }

        return LogAdPostbackMedia::STATUS_SUCC;
    }

    // 此接口由子类继承
    // 匹配成功后补齐监控数据
    public function supplementMonitorInfo(FirstupAd $firstup_ad, AdMonitor $monitor)
    {
        $data = json_decode($monitor->data, true);

        foreach (['userid', 'pid', 'uid', 'aid'] as $id) {
            $value = $data[$id] ?? 0;
            if (!is_numeric($value)) {
                $data[$id] = 0;
            }
        }

        $firstup_ad->advertiser_id = $data['userid'] ?? 0;  // 广告主id
        $firstup_ad->adgroup_id    = $data['pid'] ?? 0;     // 计划id
        $firstup_ad->ad_id         = $data['uid'] ?? 0;     // 单元id
        $firstup_ad->creative_id   = $data['aid'] ?? 0;     // 创意id
    }
}
